import isFunction from './isFunction';
import isFunctionComponent from './isFunctionComponent';
import mountNativeElement from './mountNativeElement';

export default function mountComponent(virtualDOM, container, oldDOM) {
  let nextVirtualDOM  = null
  let component = null
  // 判断是类组件还是函数组件
  if(isFunctionComponent(virtualDOM)) {
    // 函数组件 
    nextVirtualDOM = buildFunctionComponent(virtualDOM)
  } else {
    // 类组件
    nextVirtualDOM = buildClassComponent(virtualDOM)
    component = nextVirtualDOM.component
  }
  if(isFunction(nextVirtualDOM)) {
    mountComponent(nextVirtualDOM, container, oldDOM)
  }else {
    mountNativeElement(nextVirtualDOM, container, oldDOM)
  }
  if(component) {
    component.componentDidMount()
    if(component.props && component.props.ref) {
      component.props.ref(component)
    }
  }
}

// 返回函数组件的DOM
function buildFunctionComponent(virtualDOM) {
  return virtualDOM.type(virtualDOM.props || {})
}

// 返回类组件DOM
function buildClassComponent(virtualDOM) {
  // 获取类组件实例并返回render函数的结果
  const component = new virtualDOM.type(virtualDOM.props || {})
  const nextVirtualDOM = component.render()
  nextVirtualDOM.component = component
  return nextVirtualDOM
}